package database

import (
	"context"
	"egin/pkg/config"
	"fmt"
	"time"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

var _db_mongo *mongo.Client

func init() {
	uri := fmt.Sprintf("mongodb://%s:%s@%s:%s/%s?authSource=%s",
		config.C().Mongodb.User,
		config.C().Mongodb.Password,
		config.C().Mongodb.Host,
		config.C().Mongodb.Port,
		config.C().Mongodb.Dbname,
		config.C().Mongodb.Dbname,
	)

	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()
	var err error
	_db_mongo, err = mongo.Connect(ctx, options.Client().ApplyURI(uri).SetMaxPoolSize(config.C().Mongodb.SetMaxPoolSize)) // 连接池
	if err != nil {
		panic(err)
	}
}

//Db huo
func Mongo() *mongo.Client {

	return _db_mongo
}

//Db huo
func MongoDB() *mongo.Database {

	return Mongo().Database(config.C().Mongodb.Dbname)
}
